<template>
  <div class="page-container">
    <!-- 顶部标题栏 -->
    <header class="header">
      <BackBtn />
      <h1>提案详情</h1>
      <Time />
    </header>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <div class="detail-container" ref="proposalContent"  v-loading="loading" element-loading-text="加载中..." element-loading-background="rgba(0,0,0,0)">
        <!-- 提案基本信息 -->
        <div class="detail-section">
          <h2 class="section-title">提案内容</h2>
          <div class="info-grid">
            <div class="info-item">
              <span class="label">案由：</span>
              <span class="value">{{ proposalDetail.caseReason }}</span>
            </div>
            <div class="info-item">
              <span class="label">主题词：</span>
              <span class="value">{{ proposalDetail.topic }}</span>
            </div>
            <div class="info-item">
              <span class="label">提案人：</span>
              <span class="value">{{ proposalDetail.proposer }}</span>
            </div>
            <div class="info-item">
              <span class="label">联名人：</span>
              <span class="value" v-if="proposalDetail.signers">{{ proposalDetail.signers }}</span>
              <span class="value" v-else>无</span>
            </div>
            <div class="info-item">
              <span class="label">提案类型：</span>
              <span class="value">{{ proposalDetail.proposalType }}</span>
            </div>
            <div class="info-item">
              <span class="label">提交时间：</span>
              <span class="value">{{ formatDateTime(proposalDetail.submitTime) }}</span>
            </div>
            <div class="info-item">
              <span class="label">联系地址：</span>
              <span class="value">{{ proposalDetail.address }}</span>
            </div>
            <div class="info-item">
              <span class="label">提案人地区：</span>
              <span class="value">{{ proposalDetail.proposerRegion }}</span>
            </div>
            <div class="info-item">
              <span class="label">提案人邮编：</span>
              <span class="value">{{ proposalDetail.postalCode }}</span>
            </div>
            <div class="info-item">
              <span class="label">是否愿意公示：</span>
              <span class="value">{{ proposalDetail.isPublic ? '是' : '否' }}</span>
            </div>

            <div class="info-item">
              <span class="label"></span>
              <span class="value">
                <div class="proposal-content" v-html="formatProposalContent(proposalDetail.proposalContent)"></div>
              </span>
            </div>
          </div>
        </div>

        <!-- 提案附件部分 -->
        <div class="attachment-section">
          <div v-if="proposalDetail.attachments" class="attachment-list">
            <div v-for="(attachment, index) in attachmentList" :key="index" class="attachment-item">
              <span class="file-name">
                <el-link type="primary" :href="attachment" target="_blank" :underline="false">
                  {{ `附件${index + 1}&nbsp;:&nbsp;&nbsp; ${getFileName(attachment)}` }}
                </el-link>
              </span>
            </div>
          </div>
          <!-- <div v-else class="no-data">
            无提案相关附件
          </div> -->
        </div>

        <hr>


        <!-- 处理结果 -->
        <div class="result-section">
          <h3>处理结果</h3>
          <div class="info-grid">
            <div class="info-item">
              <span class="label"></span>
              <span class="value"  v-html="formatProposalContent(proposalDetail.handingResult)"></span>
            </div>
          </div>

          <!-- 处理结果附件部分 -->
          <div class="attachment-section">
            <div v-if="proposalDetail.handlingAttachments" class="attachment-list">
              <div v-for="(attachment, index) in handlingAttachmentList" :key="index" class="attachment-item">
                <span class="file-name">
                  <el-link type="primary" :href="attachment" target="_blank" :underline="false">
                    {{ `附件${index + 1}&nbsp;:&nbsp;&nbsp; ${getFileName(attachment)}` }}
                  </el-link>
                </span>
              </div>
            </div>
          </div>
        </div>


        <br>
        <hr>
        <!-- 当前状态 -->
        <div class="status-section">
          <div class="status-title"
            style="display: flex; justify-content: space-between; align-items: center;width: 95%;">
            <h3>处理状态</h3>
            <div>
              <span class="label">提案号：</span>
              <span class="value">{{ proposalDetail.pid }}</span>
            </div>
          </div>
          <div class="status-list">
            <div v-for="(stage, index) in getStatusInfo" :key="index" class="status-item" v-show="!stage.isHidden">
              <span class="status-label">{{ stage.label }}——</span>
              <span class="status-value" :style="getStatusStyle(stage)">
                {{ getStatusText(stage) }}
              </span>
            </div>
          </div>
        </div>


      </div>

     
      <div class="action-buttons-container">
        <el-button type="danger" @click="downloadProposal" :loading="isDownloading" class="action-button">
          {{ isDownloading ? '正在生成...' : '导出文档' }}
        </el-button>
        <el-button type="primary" @click="downloadAllAttachments" :loading="isDownloadingAttachments"
          class="action-button">
          {{ isDownloadingAttachments ? '正在下载...' : '下载所有附件' }}
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getProposalDetails, downloadFile, exportProposalDetailToWord } from '@/api/proposal.js'
import Time from '@/components/Time.vue'
import BackBtn from '@/components/Back-btn.vue'
import JSZip from 'jszip'
import { saveAs } from 'file-saver'
import { Document, Paragraph, TextRun, Packer } from 'docx'

const loading = ref(false) // 添加loading状态

const route = useRoute()
const router = useRouter()
const proposalDetail = ref({})
const proposalContent = ref(null)
const isDownloading = ref(false)
const isDownloadingAttachments = ref(false)

// 获取提案详情
const fetchProposalDetail = async () => {
  try {
    const proposalId = route.params.id
    const response = await getProposalDetails(proposalId)
    if (response.data) {
      proposalDetail.value = response.data
    }
  } catch (error) {
    ElMessage.error('获取提案详情失败')
    console.error('获取提案详情错误:', error)
  }
}

const attachmentList = computed(() => {
  if (proposalDetail.value.attachments) {
    return proposalDetail.value.attachments.split(',')
  }
  return []
})

const getFileName = (url) => {
  if (!url) return ''
  const parts = url.split('/')
  return parts[parts.length - 1]
}

// 下载提案内容为文档
const downloadProposal = async () => {
  try {
    isDownloading.value = true
    const proposalId = route.params.id
    
    // 调用API导出提案详情
    const response = await exportProposalDetailToWord(proposalId)
    
    // 创建Blob对象
    const blob = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' })
    
    // 获取提案编号
    const pid = proposalDetail.value.pid || proposalId
    
    // 创建下载链接
    const link = document.createElement('a')
    link.href = URL.createObjectURL(blob)
    link.download = `提案${pid}详情.docx`
    
    // 触发下载
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    
    ElMessage.success('提案导出成功')
  } catch (error) {
    console.error('导出提案失败:', error)
    ElMessage.error('导出提案失败，请重试')
  } finally {
    isDownloading.value = false
  }
}

// 添加时间格式化函数
const formatDateTime = (time) => {
  if (!time) return '待处理'
  const date = new Date(time)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}`
}

// 修改获取状态文本的函数
const getStatusText = (stage) => {
  if (stage.isHidden) return ''
  
  // 如果是已驳回状态
  if (stage.isRejected) return '已驳回'
  
  // 如果是当前正在处理的阶段
  if (isCurrentProcessingStage(stage)) return '处理中'
  
  // 如果有完成时间，说明该阶段已完成
  if (stage.time) return formatDateTime(stage.time)
  
  // 其他情况显示待处理
  return '待处理'
}

// 添加判断当前处理阶段的函数
const isCurrentProcessingStage = (stage) => {
  const { status } = proposalDetail.value
  
  // 根据当前状态判断哪个阶段是"处理中"
  switch (status) {
    case '处理中':
      return stage.label === '提案初审'
    case '初审':
      return stage.label === '提案复审'
    case '复审':
      return stage.label === '分流处理'
    case '分流':
      return stage.label === '专项处理'
    case '专项处理':
      return stage.label === '最终批复'
    case '已驳回':
      return false // 驳回状态没有"处理中"的阶段
    default:
      return false
  }
}

// 修改获取状态样式的函数
const getStatusStyle = (stage) => {
  // 如果是已驳回状态
  if (stage.isRejected) {
    return { color: '#F56C6C' } // 红色
  }
  
  // 如果是当前正在处理的阶段
  if (isCurrentProcessingStage(stage)) {
    return { color: '#409EFF' } // 蓝色
  }
  
  // 如果没有时间（未开始处理）
  if (!stage.time) {
    return { color: '#909399' } // 灰色
  }
  
  // 已完成的阶段
  return { color: '#333' } // 黑色
}

// 修改状态信息的计算属性
const getStatusInfo = computed(() => {
  const {
    status,
    submitTime,
    firstAuditTime,
    isFrist,
    recheckTime,
    isRecheck,
    shuntTime,
    isShunt,
    specialHandlingTime,
    isHanding,
    finalReplyTime,
    isFinal,
    completionTime
  } = proposalDetail.value

  // 定义状态阶段数组
  const stages = [
    {
      label: '提交时间',
      time: submitTime,
      isCompleted: !!submitTime
    },
    {
      label: '提案初审',
      time: firstAuditTime,
      isCompleted: isFrist
    },
    {
      label: '提案复审',
      time: recheckTime,
      isCompleted: isRecheck
    },
    {
      label: '分流处理',
      time: shuntTime,
      isCompleted: isShunt
    },
    {
      label: '专项处理',
      time: specialHandlingTime,
      isCompleted: isHanding
    },
    {
      label: '最终批复',
      time: finalReplyTime,
      isCompleted: isFinal
    },
    {
      label: '处理完结',
      time: completionTime,
      isCompleted: !!completionTime
    }
  ]

  // 如果状态是已驳回，找到驳回的阶段
  if (status === '已驳回') {
    let rejectedStage = null
    for (let i = stages.length - 1; i >= 0; i--) {
      const stage = stages[i]
      if (stage.time && !stage.isCompleted) {
        rejectedStage = i
        break
      }
    }

    // 标记驳回阶段及之后的状态
    if (rejectedStage !== null) {
      stages[rejectedStage].isRejected = true
      for (let i = rejectedStage + 1; i < stages.length; i++) {
        stages[i].isHidden = true
      }
    }
  }

  return stages
})

// 用于处理结果的附件
const handlingAttachmentList = computed(() => {
  if (proposalDetail.value.handlingAttachments) {
    return proposalDetail.value.handlingAttachments.split(',')
  }
  return []
})

// 下载所有附件
const downloadAllAttachments = async () => {
  try {
    isDownloadingAttachments.value = true
    const zip = new JSZip()

    // 合并提案附件和处理结果附件
    const allAttachments = [
      ...attachmentList.value.map(url => ({ url, prefix: '提案附件' })),
      ...handlingAttachmentList.value.map(url => ({ url, prefix: '处理结果附件' }))
    ]

    if (allAttachments.length === 0) {
      ElMessage.warning('没有可下载的附件')
      return
    }

    // 下载所有文件
    for (const { url, prefix } of allAttachments) {
      try {
        const response = await downloadFile(url)
        const fileName = getFileName(url)
        // 将文件添加到zip中，使用前缀区分不同类型的附件
        zip.file(`${prefix}_${fileName}`, response)
      } catch (error) {
        console.error(`下载文件失败: ${url}`, error)
        ElMessage.error(`文件 ${getFileName(url)} 下载失败`)
      }
    }

    // 生成zip文件并下载
    const content = await zip.generateAsync({ type: 'blob' })
    const zipFileName = `提案${proposalDetail.value.pid}_附件.zip`
    saveAs(content, zipFileName)

    ElMessage.success('附件打包下载成功')
  } catch (error) {
    console.error('下载附件失败:', error)
    ElMessage.error('下载附件失败，请重试')
  } finally {
    isDownloadingAttachments.value = false
  }
}

// 修改格式化函数
const formatProposalContent = (content) => {
  if (!content) return '';
  
  // 将内容按换行符分割成段落
  const paragraphs = content.split(/\n+/);
  
  return paragraphs
    .map(paragraph => {
      paragraph = paragraph.trim();
      if (!paragraph) return '';
      
      // 检查是否是数字编号的段落
      const isNumberedItem = /^\d+\./.test(paragraph);
      
      if (isNumberedItem) {
        // 处理带数字编号的段落
        const [number, ...rest] = paragraph.split(/(?<=^\d+\.)\s*/);
        return `<p class="paragraph numbered">
          <span class="number">${number}</span>
          <span class="text">${rest.join('')}</span>
        </p>`;
      } else {
        // 处理普通段落，添加首行缩进
        return `<p class="paragraph indented">${paragraph}</p>`;
      }
    })
    .join('');
};

// 在组件挂载时获取提案数据
onMounted(async () => {
  loading.value = true
  await fetchProposalDetail()
  loading.value = false
})

</script>

<style scoped>
@import '@/assets/css/header/index.css';

.page-container {
  min-height: 100vh;
  background-color: #f5f6f8;
  padding-top: 100px;
}

.main-content {
  padding: 50px;
  margin: 0 auto;
  max-width: 1200px;
  width: 80%;
}

.detail-container {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

}

.detail-section {
  margin-bottom: 30px;
}

.section-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(1, 1fr);
  gap: 20px;
  padding-left: 20px;
}

.info-item {
  display: flex;
  align-items: center;
}

.label {
  color: #666;
  min-width: 100px;
}

.value {
  color: #333;
  font-weight: 500;
  text-indent: 0;
}

.content-box {
  padding: 20px;
  background: #f8f9fa;
  border-radius: 4px;
  line-height: 1.6;
}

.attachments-list {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.attachment-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 15px;
  /* background: #f8f9fa; */
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
  margin-left: 10px;
}


.attachment-section {
  margin: 20px 0;
}


.no-data {
  color: #909399;
  text-align: center;
  padding: 20px 0;
}

.file-name {
  margin-right: 10px;
}

/* 修改按钮容器样式 */
.action-buttons-container {
  margin-top: 20px;
  text-align: center;
  padding: 20px;
  display: flex;
  justify-content: center;
  gap: 20px;
}

.action-button {
  height: 50px;
  border-radius: 10px;
  border: none;
  background-color: #cf1a1a;
  width: 180px;
  font-size: 18px;
}

.el-button:hover {
  background-color: #a21616;
}

/* 添加状态值的样式 */
.status-value {
  color: #333;
  font-weight: 500;
}

.status-value:empty::before {
  content: '待处理';
  color: #909399;
  font-weight: normal;
}

.status-list {
  padding-left: 20px;
}


.status-item {
  margin: 10px 0;
  /* 上下边距以增加行间隔 */
}

.proposal-content {
  width: 100%;
  line-height: 1.8;
}

.paragraph {
  margin: 1em 0;
  text-indent: 2em; /* 默认段落首行缩进 */
  white-space: pre-wrap; /* 保留空格和换行 */
}

/* 带编号的段落特殊处理 */
.paragraph.numbered {
  display: flex;
  text-indent: 0; /* 编号段落取消缩进 */
  padding-left: 2em; /* 整体缩进 */
}

.paragraph .number {
  flex-shrink: 0;
  margin-right: 0.5em;
}

.paragraph .text {
  flex: 1;
}

/* 普通段落的首行缩进 */
.paragraph.indented {
  text-indent: 2em; /* 设置首行缩进 */
}
</style>